using Catalog.Application.Categorys.Interfaces;
using Catalog.Application.Contracts.DTOs;
using Microsoft.EntityFrameworkCore;

namespace Catalog.Infrastructure.Persistence.ReadServices;

public class CategoryReadService : ICategoryReadService
{
    private readonly CatalogDbContext _context;

    public CategoryReadService(CatalogDbContext context)
    {
        _context = context;
    }
    public async Task<bool> ExistsAsync(Guid id)
    {
        return await _context.Categories
            .AsNoTracking()
            .AnyAsync(b => b.Id == id);
    }

    public async Task<CategoryProfileDto?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
    {
        return await _context.Categories
            .AsNoTracking()
            .Where(c => c.Id == id)
            .Select(c => new CategoryProfileDto
            {
                Id = c.Id,
                Name = c.Name,
                Description = c.Description
            })
            .FirstOrDefaultAsync(cancellationToken);

           
            
    }

    public async Task<IEnumerable<CategoryProfileDto>> GetListAsync(string? keyword = null, CancellationToken cancellationToken = default)
    {
        var query = _context.Categories.AsNoTracking().AsQueryable();

        if (!string.IsNullOrEmpty(keyword))
        {
            query = query.Where(c => c.Name.Contains(keyword));
        }

        return await query.Select(c => new CategoryProfileDto
        {
            Id = c.Id,
            Name = c.Name,
            Description = c.Description
        }).ToListAsync(cancellationToken);
    }
}